import React, { useState } from 'react';
import { Upload, Button, message, Modal } from 'antd';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';
export default function TagImg() {
  // 转变为受控组件,数据的双向绑定，监控数组里面的随时变化
  const [imgView, setImgView] = useState('');
  const [fileList, setFileList] = useState([]);
  const props = {
    name: 'image',
    accept: '.png,.jpg', //浏览器打开窗口右下角有格式限定
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    onChange(info) {
      setFileList(info.fileList);
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
    onPreview(file) {
      // console.log('Your upload file:', file);
      // Your process logic. Here we just mock to the same file
      setImgView(file.thumbUrl);
    },
    // 限制上传图片类型
    beforeUpload(file) {
      //  白名单
      let whiteImg = ['image/png', 'image/jpg'];
      if (!whiteImg.includes(file.type)) {
        message.warning('请选择正确的图片格式');
        return Upload.LIST_IGNORE;
      }
    },
  };
  return (
    <>
      <Upload listType="picture-card" {...props} fileList={fileList}>
        {fileList.length === 3 ? null : <Button>哈哈哈</Button>}
      </Upload>
      <Modal
        title="预览图片"
        visible={!!imgView}
        footer={null}
        onCancel={() => setImgView('')}
        style={{ textAlign: 'center' }}
      >
        <img
          src={imgView}
          alt=""
          width={370}
          style={{ objectFit: 'cover' }}
        ></img>
      </Modal>
    </>
  );
}
